<template>
  <div class="dashboard-container">
    <div class="dashboard-text">{{ name }},欢迎回来！</div>
    <div class="dashboard-content">
      <div class="chart-top">
        <div class="box animate__animated animate__bounce" style="color: #ec8080">
          <i class="el-icon-user"></i>
          <div>
            <div>累计注册用户数</div>
            <div style="font-size: 50px">{{ topData.user_cnt }}</div>
          </div>
        </div>
        <div class="box animate__animated animate__bounce" style="color: #efa773">
          <i class="el-icon-view"></i>
          <div>
            <div>累计课堂浏览数</div>
            <div style="font-size: 50px">{{ topData.visit_cnt }}</div>
          </div>
        </div>
        <div class="box animate__animated animate__bounce" style="color: #92ddfd">
          <i class="el-icon-chat-line-round"></i>
          <div>
            <div>累计用户评论数</div>
            <div style="font-size: 50px">{{ topData.comment_cnt }}</div>
          </div>
        </div>
        <div class="box animate__animated animate__bounce" style="color: #92a4fd">
          <i class="el-icon-files"></i>
          <div>
            <div>累计课堂资源数</div>
            <div style="font-size: 50px">{{ topData.resource_cnt }}</div>
          </div>
        </div>
      </div>
      <div ref="chart" class="chart-middle">
      </div>
      <div class="chart-bottom">
        <div class="box">
          <DoughnutChart title="师生比例" :chartData="bingData[0]" ref="ch1"/>
        </div>
        <div class="box" style="flex: 2">
          <BasicBarChart :data="pointData" ref="ch2"/>
        </div>
        <div class="box">
          <DoughnutChart title="性别比例" :chartData="bingData[1]" ref="ch3"/>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {mapGetters} from 'vuex'
import * as echarts from 'echarts';
import RoseChart from "@/views/dashboard/component/RoseChart.vue";
import BasicBarChart from "@/views/dashboard/component/BasicBarChart.vue";
import DoughnutChart from "@/views/dashboard/component/DoughnutChart.vue";
import {getHomeBing, getHomeDaysData, getHomePoint, getHomeTopData} from "@/api/home/base";

export default {
  name: 'Dashboard',
  components: {DoughnutChart, BasicBarChart, RoseChart},
  computed: {
    ...mapGetters([
      'name'
    ]),
  },

  data() {
    return {
      bingData: [],
      pointData: {},
      valueData: {
        title: null,
        loginData: null,
        commentData: null
      },
      myChart: null,
      chartOption: {
        title: {
          text: "近七日数据统计"
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['登录人数', '评论数']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: ['近1日', '近2日', '近3日', '近4日', '近5日', '近6日', '近7日']
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '评论数',
            type: 'line',
            data: []
          },
          {
            name: '登录人数',
            type: 'line',
            data: []
          },
        ]
      },
      topData: {}
    };
  },
  mounted() {
    this.fetchTopData()
    this.fetchDaysData()
    this.fetchBingData()
    this.fetchPointData()
    this.initChart();
    this.observeChartResize()
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
    if (this.myChart) {
      this.myChart.dispose();
    }
  },
  updated() {
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    initChart() {
      this.$nextTick(() => {
        this.myChart = echarts.init(this.$refs.chart)
        this.myChart.setOption(this.chartOption);
      })

    },
    observeChartResize() {
      // 如果浏览器支持 ResizeObserver
      if (typeof ResizeObserver !== 'undefined') {
        this.resizeObserver = new ResizeObserver(() => {
          if (this.myChart) {
            this.myChart.resize(); // 调整图表大小
          }
        });
        this.resizeObserver.observe(this.$refs.chart); // 监听容器
      } else {
        // 如果不支持，降级使用 window.resize
        window.addEventListener('resize', this.handleResize);
      }
    },
    handleResize() {
      this.myChart && this.myChart.resize()
    },
    async fetchTopData() {
      this.topData = await getHomeTopData()
    },
    async fetchDaysData() {
      const rep = await getHomeDaysData()
      console.log("apiData", rep)
      // 按日期顺序排序（近1日 → 近7日）
      const sortedKeys = Object.keys(rep.commentData).sort((a, b) => {
        const numA = parseInt(a.match(/\d+/)[0]);
        const numB = parseInt(b.match(/\d+/)[0]);
        return numA - numB;
      })

      // 生成两个数组
      this.valueData.title = sortedKeys;
      this.valueData.commentData = sortedKeys.map(key => rep.commentData[key]);
      this.valueData.loginData = sortedKeys.map(key => rep.loginData[key]);

      this.chartOption.series[0].data = this.valueData.commentData
      this.chartOption.series[1].data = this.valueData.loginData

      this.myChart.setOption(this.chartOption);
    },
    async fetchBingData() {
      const rep = await getHomeBing()
      this.bingData[0] = rep[0]
      this.bingData[1] = rep[1]
      console.log(this.bingData)

      this.$nextTick(() => {
        this.$refs.ch1.updateChart(this.bingData[0])
        this.$refs.ch3.updateChart(this.bingData[1])
      })

    },
    async fetchPointData() {
      const rep = await getHomePoint()
      // 提取 point_content 数组
      const pointContentArray = rep.map(item => item.point_content)
      // 提取 qs_cnt 数组
      const qsCntArray = rep.map(item => item.qs_cnt);
      this.pointData.pointContentArray = pointContentArray
      this.pointData.qsCntArray = qsCntArray
      this.$nextTick(() => {
        this.$refs.ch2.updateChart()
      })
      // console.log("pointdata", this.pointData)
    }
  },
}
</script>

<style lang="scss" scoped>
.dashboard {
  &-container {
    margin: 30px;
  }

  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}

.chart-top {
  display: flex;
  align-items: center;
  justify-content: space-around;

  .box {
    display: flex;
    align-items: center;
    justify-content: space-around;
    flex: 1;
    padding: 20px;
    margin: 20px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);

    i {
      font-size: 50px;
    }
  }
}

.chart-middle {
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
  width: 90%;
  height: 50vh;
  margin: 0 auto;
}

.chart-bottom {
  display: flex;
  align-items: center;
  justify-content: space-around;

  .box {
    flex: 1;
    padding: 20px;
    margin: 20px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
  }
}
</style>
